import { AttrData } from './types';
import conf from './config';
import { isJSON } from './tools';
import LZString from './lz-string';
import { encrypt, decrypt } from './encrypt';

export function jsonToData(text: string): object {
  let content: string | null = text;
  if (conf.encryptType === 1) {
    // 混淆加密
    content = decrypt(text);
  } else if (conf.encryptType === 2) {
    // 压缩加密
    content = LZString.decompress(text);
  }
  if (content) {
    if (isJSON(content)) {
      return JSON.parse(content);
    }
    return { text: content };
  }
  return { text: '' };
}

export function dataToJson(data: string|object): string {
  let content: string | null;
  if (typeof data === 'object') {
    content = JSON.stringify(data);
  } else {
    content = data;
  }
  if (conf.encryptType === 1) {
    // 混淆加密
    content = encrypt(content);
  } else if (conf.encryptType === 2) {
    // 压缩加密
    content = LZString.compress(content);
  }
  return content;
}

export function setAttrData(data: AttrData = {}) {
  const attrData: any = {};
  const { clickData, viewData } = data;
  if (clickData) {
    attrData[conf.clickAttr as string] = dataToJson(typeof clickData === 'string' ? { valBid: clickData } : clickData);
  }
  if (viewData) {
    attrData[conf.viewAttr as string] = dataToJson(typeof viewData === 'string' ? { valBid: viewData } : viewData);
  }
  return attrData;
}

export default {
  jsonToData,
  dataToJson,
  setAttrData,
};
